package edu.nf.project.webs.other;

import edu.nf.project.entitys.entity.other.Message;
import edu.nf.project.services.exception.derivedAnomalies.MessageException;
import edu.nf.project.services.other.MessageService;
import edu.nf.project.services.response.BaseController;
import edu.nf.project.services.response.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 消息管理控制器
 */
@RestController
@RequestMapping("/api/messages")
public class MessageController extends BaseController {
    @Autowired
    private MessageService messageService;

    /**
     * 发送消息
     * @param message 消息内容
     * @return 响应对象
     */
    @PostMapping
    public ResultVO<Void> sendMessage(@RequestBody Message message) {
        try {
            messageService.sendMessage(message);
            return success();
        } catch (Exception e) {
            if (e instanceof MessageException) {
                throw e;
            }
            throw new MessageException(80000, "消息发送失败：" + e.getMessage());
        }
    }

    /**
     * 获取聊天历史记录
     * @param sender 发送者ID
     * @param receiver 接收者ID
     * @return 消息列表
     */
    @GetMapping
    public ResultVO<List<Message>> getChatHistory(
            @RequestParam String sender,
            @RequestParam String receiver) {
        try {
            List<Message> messages = messageService.getChatHistory(sender, receiver);
            return success(messages);
        } catch (Exception e) {
            if (e instanceof MessageException) {
                throw e;
            }
            throw new MessageException(80001, "获取聊天记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有聊天记录
     * @param receiver 接收者ID
     * @return 聊天列表
     */
    @GetMapping("/all")
    public ResultVO<List<Map<String, Object>>> getAllChats(@RequestParam String receiver) {
        try {
            List<Message> allMessages = messageService.getAllChats(receiver);
            
            // 按发送者分组，获取每个发送者的最后一条消息
            Map<String, List<Message>> groupedMessages = allMessages.stream()
                .collect(Collectors.groupingBy(Message::getSender));
            
            // 转换为前端需要的格式
            List<Map<String, Object>> chats = groupedMessages.entrySet().stream()
                .map(entry -> {
                    List<Message> messages = entry.getValue();
                    // 按时间排序
                    messages.sort((a, b) -> b.getSendTime().compareTo(a.getSendTime()));
                    // 获取最后一条消息
                    Message lastMessage = messages.get(0);
                    
                    Map<String, Object> chat = new HashMap<>();
                    chat.put("sender", entry.getKey());
                    chat.put("lastMessage", lastMessage.getContent());
                    chat.put("lastMessageTime", lastMessage.getSendTime().getTime());
                    chat.put("unreadCount", 0);
                    return chat;
                })
                .collect(Collectors.toList());
            
            return success(chats);
        } catch (Exception e) {
            if (e instanceof MessageException) {
                throw e;
            }
            System.out.println(e);
            throw new MessageException(80002, "获取所有聊天记录失败：" + e.getMessage());
        }
    }
}
